﻿using UnityEngine;

/// <summary>
/// 单例基类，继承此类的子类将成为单例对象
/// </summary>
public class Singleton<T> : MonoBehaviour where T : MonoBehaviour
{
    private static T _instance;

    // 对外暴露的单例实例
    public static T Instance
    {
        get
        {
            if (_instance == null)
            {
                // 查找场景中是否已经存在该单例
                _instance = FindObjectOfType<T>();

                if (_instance == null)
                {
                    // 如果没有找到，则创建一个新的GameObject并附加单例组件
                    GameObject singletonObject = new GameObject(typeof(T).Name);
                    _instance = singletonObject.AddComponent<T>();
                }
            }
            return _instance;
        }
    }


}